//
//  SJFriendViewController.m
//  WSL
//
//  Created by CJ on 2017/10/18.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJFriendViewController.h"
#import "SJUserItem.h"
#import "SJFriendCell.h"
#import "SJCustomLayout.h"
#import "SJStyleItem.h"
#import "SJWordItem.h"
#import "SJFriendMineApi.h"
#import "SJGetStyleApi.h"

#import "SJFriendOneViewController.h"

@interface SJFriendViewController () <UICollectionViewDataSource, UICollectionViewDelegate, SJCustomLayoutDelegate>

@property (strong, nonatomic) SJCustomLayout *customLayout;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@property (nonatomic, strong) UIView *tabBarContainView;
@property (nonatomic, strong) UIButton *profileButton;
@property (nonatomic, strong) UIButton *searchButton;
@property (nonatomic, strong) UIButton *outsideButton;

@property (nonatomic, assign) CGFloat translationY;

@end

@implementation SJFriendViewController

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    //scrollView已经有拖拽手势，直接拿到scrollView的拖拽手势
    UIPanGestureRecognizer *pan = scrollView.panGestureRecognizer;
    CGFloat translationY = [pan translationInView:scrollView].y;
    
    if (self.translationY == translationY) {
        return;
    }
    
    self.translationY = translationY;
    WeakSelf;
    if (translationY < -20) {
        //向上拖动，隐藏导航栏
        [UIView animateWithDuration:.5 animations:^{
            weakSelf.tabBarContainView.sd_layout.topSpaceToView(weakSelf.view, -SJLayoutFrame(64));
            [weakSelf.tabBarContainView updateLayout];
        }];
        
    } else if (translationY > 0) {
        //向下拖动，显示导航栏
        [UIView animateWithDuration:.5 animations:^{
            weakSelf.tabBarContainView.sd_layout.topSpaceToView(weakSelf.view, 0);
            [weakSelf.tabBarContainView updateLayout];
        }];
        
    } else if (translationY == 0) {
        //停止拖拽
        
    }
}
- (void)dealloc {
    SJLogFunc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
    [self loadNewData];
}

- (void)setupUI {
    
    [self.view addSubview:self.collectionView];
    self.collectionView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    
    [self.view addSubview:self.tabBarContainView];
    self.tabBarContainView.sd_layout
    .topSpaceToView(self.view, SJLayoutFrame(0))
    .rightSpaceToView(self.view, SJLayoutFrame(0))
    .heightIs(SJLayoutFrame(64))
    .widthIs(SJScreenW);
}

#pragma mark - getter

- (UIView *)tabBarContainView{
    
    if (!_tabBarContainView) {
        _tabBarContainView = [UIView new];
        
        CGFloat itemWH = SJScreenW / 6;
        
        [_tabBarContainView addSubview:self.outsideButton];
        self.outsideButton.sd_layout
        .topSpaceToView(_tabBarContainView, 0)
        .leftSpaceToView(_tabBarContainView, itemWH * 0)
        .heightIs(itemWH)
        .widthIs(itemWH);
        
    }
    return _tabBarContainView;
}

- (SJCustomLayout *)customLayout{
    
    if (!_customLayout) {
        _customLayout = [[SJCustomLayout alloc] init];
        _customLayout.delegate = self;
        
    }
    return _customLayout;
}


- (void)friendAction:(UIButton *)button {
    
    if (button == self.outsideButton) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

/**
 profileButton
 */
- (UIButton *)profileButton{
    
    if (!_profileButton) {
        
        _profileButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_profileButton addTarget:self action:@selector(friendAction:) forControlEvents:UIControlEventTouchUpInside];
        [_profileButton setImage:[UIImage imageNamed:@"home_profile_btn"] forState:UIControlStateNormal];
        
    }
    return _profileButton;
}

/**
 searchButton
 */
- (UIButton *)searchButton{
    
    if (!_searchButton) {
        
        _searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_searchButton addTarget:self action:@selector(friendAction:) forControlEvents:UIControlEventTouchUpInside];
        [_searchButton setImage:[UIImage imageNamed:@"home_search_btn"] forState:UIControlStateNormal];
        
    }
    return _searchButton;
}

/**
 outsideButton
 */
- (UIButton *)outsideButton{
    
    if (!_outsideButton) {
        
        _outsideButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_outsideButton addTarget:self action:@selector(friendAction:) forControlEvents:UIControlEventTouchUpInside];
        [_outsideButton setImage:[UIImage imageNamed:@"home_outside_btn"] forState:UIControlStateNormal];
        
    }
    return _outsideButton;
}

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.customLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.contentInset = UIEdgeInsetsMake(SJLayoutFrame(64), 0, 0, 0);
        
        if ([_collectionView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
            if (@available(iOS 11.0, *)) {
                _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            } else {
                // Fallback on earlier versions
            }
        }
        
        [_collectionView registerClass:[SJFriendCell class] forCellWithReuseIdentifier:NSStringFromClass([SJFriendCell class])];
        
        // header
        _collectionView.mj_header = [SJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        // footer
//        _collectionView.mj_footer = [SJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    }
    
    return _collectionView;
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
        
    }
    return _dataArray;
}

#pragma mark - SJCustomLayoutDelegate

- (CGRect)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout frameOfItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat margin = SJLayoutFrame(10);
    CGFloat itemWH = (SJScreenW - 7 * margin) / 6;
    
    CGFloat w = 6 * itemWH + (6 - 1) * margin;
    CGFloat h = 2 * itemWH + (2 - 1) * margin;
    CGFloat x = margin;
    CGFloat y = (h + margin) * indexPath.row; 
    
    return CGRectMake(x, y, w, h);
}

- (CGFloat)bottomMarginInCollectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout {
    
    return SJLayoutFrame(10);
}


#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    // 根据数据量显示或者隐藏footer
    self.collectionView.mj_footer.hidden = (self.dataArray.count == 0);
    return self.dataArray.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJFriendCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJFriendCell class]) forIndexPath:indexPath];
    
    SJUserItem *item = self.dataArray[indexPath.row];
    cell.item = item;
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJUserItem *fItem = self.dataArray[indexPath.row];
    
    SJWordItem *item = [SJWordItem new];
    item.content = fItem.name;
    item.fmt = @"1";
    item.bid = @"0";
    item.ID = @"-1";
    
    SJFriendOneViewController *oneVC = [SJFriendOneViewController new];
    oneVC.item = item;
    oneVC.fItem = fItem;
    [self.navigationController pushViewController:oneVC animated:YES];
}

// 以下方法可以全部注释，注释后失去长按放大效果
#pragma mark - ---------- 允许长按 ----------
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

#pragma mark - ---------- didHighlight ----------
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *selectedCell = [collectionView cellForItemAtIndexPath:indexPath];
    [collectionView bringSubviewToFront:selectedCell];
    [UIView animateWithDuration:0.25 animations:^{
        selectedCell.transform = CGAffineTransformMakeScale(1.02f, 1.02f);
    }];
}

#pragma mark - ---------- didUnhighlight ----------
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *selectedCell = [collectionView cellForItemAtIndexPath:indexPath];
    [UIView animateWithDuration:0.25 animations:^{
        selectedCell.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
    }];
}

#pragma mark - request

- (void)loadNewData {
    
    // 1.拼接参数
    self.page = 0;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%ld", (long)self.page];
    
    SJFriendMineApi *api = [[SJFriendMineApi alloc] initWithParameters:parameters];
    
    if ([api loadCacheWithError:nil]) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            self.dataArray = [[NSArray modelArrayWithClass:[SJUserItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            [self.collectionView reloadData];
        }
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            self.dataArray = [[NSArray modelArrayWithClass:[SJUserItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            [self.collectionView reloadData];
        }
        [self.collectionView.mj_header endRefreshing];
    
    } failure:^(YTKBaseRequest *request) {
        [self.collectionView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData {
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%d", ++self.page];
    
    SJFriendMineApi *api = [[SJFriendMineApi alloc] initWithParameters:parameters];
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [self.dataArray addObjectsFromArray:[NSArray modelArrayWithClass:[SJUserItem class] json:api.responseObject[@"content"][@"data"]]];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            [self.collectionView reloadData];
            
        } else {
            
            self.page--;
        }
        
        [self.collectionView.mj_footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        
        [self.collectionView.mj_footer endRefreshing];
        self.page--;
    }];
}


@end
